package com.blogs.ui;

import java.util.ArrayList;

import com.blogs.component.ChannelAdapter;
import com.blogs.component.HomeAdapter;
import com.blogs.component.HomeBaseActivity;
import com.blogs.component.RefreshListView;
import com.blogs.component.RefreshListView.OnMoreListener;
import com.blogs.component.RefreshListView.OnRefreshListener;
import com.blogs.entity.AppEnums;
import com.blogs.entity.ChannelFeed;
import com.blogs.entity.Feed;
import com.blogs.entity.ListDate;
import com.blogs.service.GetTimeLine;
import com.blogs.tools.DBSharedPreferences;
import com.blogs.tools.LoadingGif;
import com.blogs.tools.LoadingGif.OnReloadListener;
import com.blogs.tools.Screen;
import com.cnblogs.R;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.TextView;

public class CnblogsMainActivity extends HomeBaseActivity implements OnItemClickListener, OnItemLongClickListener,
		OnClickListener {
	enum getDataMethod {
		init, // 初始化
		more, // 点击更多
		pull// 点击下拉
	}// 获取数据方式

	private DBSharedPreferences sp;

	private ArrayList<Feed> feedList;
	private ArrayList<ChannelFeed> channelList;
	private LoadingGif loadingGif;
	private LinearLayout main_list_ll;
	private RefreshListView listView;
	private ListView channel_list;
	private HomeAdapter adapter;
	private ChannelAdapter channelAdapter;

	private boolean ismoreing = false;
	private boolean isShow;
	private boolean rightIsShow;
	private String curChannel = "";
	private int curpage = 1;

	private PopupWindow popupWindow;
	private PopupWindow rightMenuWindow;
	private Button right_menu_user_btn;
	private Button right_menu_ing_btn;
	private Button right_menu_write_btn;
	private Button right_menu_collect_btn;

	private TextView title_include_title;
	private Button title_include_channel_btn;
	private Button title_right_menu;
	private RelativeLayout title_top_bg;
	private LinearLayout popup_root;
	private RelativeLayout channel_list_top_rl;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		main_list_ll = (LinearLayout) findViewById(R.id.main_list_ll);
		sp = new DBSharedPreferences(this);
		title_include_channel_btn = (Button) findViewById(R.id.title_include_channel_btn);
		ViewGroup headview = (ViewGroup) findViewById(R.id.main_title_include);
		title_include_title = (TextView) headview.findViewById(R.id.title_include_title);
		title_right_menu = (Button) headview.findViewById(R.id.title_right_menu);
		title_top_bg = (RelativeLayout) headview;
		initPopupWindow();// 初始化弹窗

		title_right_menu.setVisibility(View.VISIBLE);
		title_right_menu.setOnClickListener(this);
		title_include_channel_btn.setVisibility(View.VISIBLE);
		title_include_channel_btn.setOnClickListener(this);

		listView = new RefreshListView(this);
		listView.setonRefreshListener(new OnRefreshListener() {

			public void onRefresh() {
				// TODO Auto-generated method stub
				// 刷新
				RefreshData();
			}
		});
		listView.setonMoreListener(new OnMoreListener() {

			public void onGetMore() {
				// TODO Auto-generated method stub
				// 更多
				if (!ismoreing) {
					ismoreing = true;
					GetMoreData();
				}
			}
		});
		listView.setOnItemClickListener(this);
		listView.setOnItemLongClickListener(this);
		loadingGif = new LoadingGif(this, listView, main_list_ll, sp);
		loadingGif.setOnReloadListener(new OnReloadListener() {

			public void onClick() {
				// TODO Auto-generated method stub
				loadingGif.showLoading();
				RefreshData();
			}
		});
		this.InitSkin();
		this.requestData();

	}

	private void InitSkin() {
		if (sp.GetIsDarkState()) {
			title_top_bg.getBackground().setLevel(2);
			main_list_ll.getBackground().setLevel(2);
			popup_root.getBackground().setLevel(2);
			channel_list_top_rl.getBackground().setLevel(2);
		} else {
			title_top_bg.getBackground().setLevel(1);
			main_list_ll.getBackground().setLevel(1);
			popup_root.getBackground().setLevel(1);
			channel_list_top_rl.getBackground().setLevel(1);
		}
		if(sp.GetSessionID().equals(""))
		{
			title_right_menu.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_icon_login));
		}
		else
		{
			title_right_menu.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_title_fav));
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		this.InitSkin();
		if (adapter != null) {
			adapter.notifyDataSetChanged();

		}
		channelAdapter.notifyDataSetChanged();
	}

	private void initPopupWindow() {
//		channelList = new ArrayList<ChannelFeed>();
//		channelList.add(new ChannelFeed("channel_big_all", "全部", "", true));
//
//		channelList.add(new ChannelFeed("channel_big_net", ".NET技术", "cate1/108698/", true));
//		channelList.add(new ChannelFeed("channel_small_cate_beginner", ".NET新手区", "cate/beginner/", false));
//		channelList.add(new ChannelFeed("channel_small_cate_aspnet", "ASP.NET", "cate/aspnet/", false));
//		channelList.add(new ChannelFeed("channel_small_cate_csharp", "C#", "cate/csharp/", false));
//		channelList.add(new ChannelFeed("channel_small_cate_winform", "WinForm", "cate/winform/", false));
//		channelList.add(new ChannelFeed("channel_small_cate_silverlight", "Silverlight", "cate/silverlight/", false));
//		channelList.add(new ChannelFeed("channel_small_cate_wcf", "WCF", "cate/wcf/", false));
//		channelList.add(new ChannelFeed("channel_small_cate_wpf", "WPF", "cate/wpf/", false));
//		channelList.add(new ChannelFeed("channel_small_cate_mvc", "ASP.NET MVC", "cate/mvc/", false));
//		channelList.add(new ChannelFeed("channel_small_cate_control", "控件开发", "cate/control/", false));
//		channelList.add(new ChannelFeed("channel_small_cate_ef", "Entity Framework", "cate/ef/", false));
//		channelList.add(new ChannelFeed("channel_small_cate_winrt_metro", "WinRT/Metro", "cate/winrt_metro/", false));
//
//		channelList.add(new ChannelFeed("channel_big_cate1_2", "编程语言", "cate1/2/", true));
//		channelList.add(new ChannelFeed("channel_small_cate_java", "Java", "cate/java/", false));
//		channelList.add(new ChannelFeed("channel_small_cate_cpp", "C++", "cate/cpp/", false));
//		channelList.add(new ChannelFeed("channel_small_cate_php", "PHP", "cate/php/", false));
//		channelList.add(new ChannelFeed("channel_small_cate_python", "Python", "cate/python/", false));
//		channelList.add(new ChannelFeed("channel_small_cate_c", "C", "cate/c/", false));
//
//		channelList.add(new ChannelFeed("channel_big_cate1_108701", "软件设计", "cate1/108701/", true));
//		channelList.add(new ChannelFeed("channel_small_cate_design", "架构设计", "cate/design/", false));
//		channelList.add(new ChannelFeed("channel_small_cate_108702", "面向对象", "cate/108702/", false));
//		channelList.add(new ChannelFeed("channel_small_cate_dp", "设计模式", "cate/dp/", false));
//
//		channelList.add(new ChannelFeed("channel_big_cate1_108703", "Web前端", "cate1/108703/", true));
//		channelList.add(new ChannelFeed("channel_small_cate_web", "Html/Css", "cate/web/", false));
//		channelList.add(new ChannelFeed("channel_small_cate_javascript", "JavaScript", "cate/javascript/", false));
//		channelList.add(new ChannelFeed("channel_small_cate_jquery", "JQuery", "cate/jquery/", false));
//		channelList.add(new ChannelFeed("channel_small_cate_html5", "HTML5", "cate/html5/", false));
//
//		channelList.add(new ChannelFeed("channel_big_cate1_108705", "手机开发", "cate1/108705/", true));
//		channelList.add(new ChannelFeed("channel_small_cate_android", "Android开发", "cate/android/", false));
//		channelList.add(new ChannelFeed("channel_small_cate_ios", "IOS开发", "cate/ios/", false));
//		channelList.add(new ChannelFeed("channel_small_cate_wp", "Windows Phone", "cate/wp/", false));
//		channelList.add(new ChannelFeed("channel_small_cate_wm", "Windows Mobile", "cate/wm/", false));
//
//		channelList.add(new ChannelFeed("channel_big_cate1_108709", "软件工程", "cate1/108709/", true));
//		channelList.add(new ChannelFeed("channel_small_cate_agile", "敏捷开发", "cate/agile/", false));
//		channelList.add(new ChannelFeed("channel_small_cate_pm", "项目与团队管理", "cate/pm/", false));
//		channelList.add(new ChannelFeed("channel_small_cate_pm", "软件工程其他", "cate/pm/", false));
//
//		channelList.add(new ChannelFeed("channel_big_cate1_108712", "数据库技术", "cate1/108712/", true));
//		channelList.add(new ChannelFeed("channel_small_cate_sqlserver", "SqlServer", "cate/sqlserver/", false));
//		channelList.add(new ChannelFeed("channel_small_cate_oracle", "Oracle", "cate/oracle/", false));
//		channelList.add(new ChannelFeed("channel_small_cate_mysql", "MySQL", "cate/mysql/", false));
//		channelList.add(new ChannelFeed("channel_small_cate_nosql", "NoSQL", "cate/nosql/", false));
//		channelList.add(new ChannelFeed("channel_small_cate_database", "其他数据库", "cate/database/", false));
		
		channelList=ListDate.GetChannelList();

		curChannel = channelList.get(sp.GetChannelIndex()).channel_url;
		if (sp.GetChannelIndex() != 0) {
			title_include_title.setText(channelList.get(sp.GetChannelIndex()).channel_text);
		} else {
			title_include_title.setText("博客园");
		}
		LayoutInflater inflater = LayoutInflater.from(this);
		View layout = inflater.inflate(R.layout.channel_popup, null);
		popup_root = (LinearLayout) layout;
		channel_list_top_rl = (RelativeLayout) layout.findViewById(R.id.channel_list_top_rl);
		Screen screen = new Screen(this);
		popupWindow = new PopupWindow(layout, screen.getScreenWidth() - 40, screen.getScreenHeight() - 120);
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		popupWindow.setOnDismissListener(new OnDismissListener() {

			public void onDismiss() {
				// TODO Auto-generated method stub
				title_include_channel_btn.setBackgroundResource(R.drawable.channel_btn);
				isShow = false;
			}
		});
		isShow = false;
		channel_list = (ListView) layout.findViewById(R.id.channel_list_lv);
		channel_list.setDivider(getResources().getDrawable(R.drawable.line_01));
		channel_list.setCacheColorHint(Color.TRANSPARENT);
		channelAdapter = new ChannelAdapter(this, channelList);
		channel_list.setAdapter(channelAdapter);
		channel_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				// TODO Auto-generated method stub
				curpage = 1;
				sp.SetChannelIndex(position);
				curChannel = channelList.get(position).channel_url;
				channelAdapter.notifyDataSetChanged();
				requestData();
				if (position != 0)
					title_include_title.setText(channelList.get(position).channel_text);
				else
					title_include_title.setText("博客园");
				listView.onRefreshComplete();
				popupWindow.dismiss();
			}
		});

		// 初始化右边菜单弹窗
		View right_menu_layout = inflater.inflate(R.layout.right_menu_popup, null);
		right_menu_user_btn = (Button) right_menu_layout.findViewById(R.id.right_menu_user_btn);
		right_menu_ing_btn=(Button) right_menu_layout.findViewById(R.id.right_menu_ing_btn);
		right_menu_write_btn = (Button) right_menu_layout.findViewById(R.id.right_menu_write_btn);
		right_menu_collect_btn = (Button) right_menu_layout.findViewById(R.id.right_menu_collect_btn);
		right_menu_user_btn.setOnClickListener(this);
		right_menu_ing_btn.setOnClickListener(this);
		right_menu_write_btn.setOnClickListener(this);
		right_menu_collect_btn.setOnClickListener(this);
		int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
		int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
		right_menu_layout.measure(w, h);
		rightMenuWindow = new PopupWindow(right_menu_layout, right_menu_layout.getMeasuredWidth(),
				right_menu_layout.getMeasuredHeight());
		Log.i("rightMenuWindow", right_menu_layout.getMeasuredWidth() + "," + right_menu_layout.getMeasuredHeight());
		rightMenuWindow.setBackgroundDrawable(new BitmapDrawable());
		rightMenuWindow.setOnDismissListener(new OnDismissListener() {

			public void onDismiss() {
				// TODO Auto-generated method stub
				rightIsShow = false;
			}
		});
		rightIsShow = false;
	}

	private void requestData() {
		loadingGif.showLoading();
		this.sendHomeTimeLine("", "", getDataMethod.init);
	}

	private void RefreshData() {
		curpage = 1;
		String sinceid = feedList != null ? feedList.get(0).blog_id : "";
		this.sendHomeTimeLine(sinceid, "", getDataMethod.pull);
	}

	private void GetMoreData() {
		curpage++;
		String maxid = feedList.get(feedList.size() - 1).blog_id;
		this.sendHomeTimeLine("", maxid, getDataMethod.more);
	}

	public void updateRequestData(getDataMethod gdm) {
		if (adapter != null) {
			adapter.notifyDataSetChanged();
			if (gdm == getDataMethod.init || gdm == getDataMethod.pull) {
				listView.setAdapter(adapter);
			}
		} else {
			adapter = new HomeAdapter(this, feedList);
			listView.setAdapter(adapter);
		}

		loadingGif.showData();
		listView.onRefreshComplete();

	}

	private void sendHomeTimeLine(String since_id, String max_id, final getDataMethod gdm) {
		new GetTimeLine(this, curChannel, curpage, since_id, max_id, new GetTimeLine.IMsgCallBack() {

			public void onSuccess(ArrayList<Feed> feeds) {
				// TODO Auto-generated method stub
				if (feedList == null)
					feedList = new ArrayList<Feed>();
				if (gdm == getDataMethod.init || gdm == getDataMethod.pull) {
					feedList.clear();
				}
				for (int i = 0; i < feeds.size(); i++) {
					feedList.add(feeds.get(i));
				}
				if (gdm == getDataMethod.more) {
					ismoreing = false;
					listView.onMoreComplete();
				}
				updateRequestData(gdm);
			}

			public void onFailed() {
				// TODO Auto-generated method stub
				loadingGif.showFiale();
			}
		}).loadData();
	}

	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		// TODO Auto-generated method stub
		if (position > feedList.size())
			return;
		Intent intent = new Intent();
		intent.setClass(this, ContentActivity.class);
		intent.putExtra("Id", feedList.get(position - 1).blog_id);
		intent.putExtra("Title", feedList.get(position - 1).title);
		intent.putExtra("Author", feedList.get(position - 1).author);
		intent.putExtra("publicDate", feedList.get(position - 1).public_time);
		intent.putExtra("ViewCount", feedList.get(position - 1).hit);
		intent.putExtra("CommentCount", feedList.get(position - 1).comment);
		intent.putExtra("url", feedList.get(position - 1).blog_url);
		intent.putExtra("blogapp", feedList.get(position - 1).blogapp);
		intent.putExtra("type", AppEnums.EnumContentType.blog);
		startActivity(intent);

	}

	public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
		// TODO Auto-generated method stub
		String[] items = { "查看正文", "查看评论", "查看博主", "取消" };
		new AlertDialog.Builder(CnblogsMainActivity.this).setItems(items, new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				switch (which) {
				case 0:
					Intent intent_con = new Intent();
					intent_con.setClass(CnblogsMainActivity.this, ContentActivity.class);
					intent_con.putExtra("Id", feedList.get(position - 1).blog_id);
					intent_con.putExtra("Title", feedList.get(position - 1).title);
					intent_con.putExtra("Author", feedList.get(position - 1).author);
					intent_con.putExtra("publicDate", feedList.get(position - 1).public_time);
					intent_con.putExtra("ViewCount", feedList.get(position - 1).hit);
					intent_con.putExtra("CommentCount", feedList.get(position - 1).comment);
					intent_con.putExtra("url", feedList.get(position - 1).blog_url);
					intent_con.putExtra("blogapp", feedList.get(position - 1).blogapp);
					intent_con.putExtra("type", AppEnums.EnumContentType.blog);
					startActivity(intent_con);
					break;
				case 1:
					Intent intent_com = new Intent();
					intent_com.setClass(CnblogsMainActivity.this, CommentActivity.class);
					intent_com.putExtra("comment_id", feedList.get(position - 1).blog_id);
					intent_com.putExtra("Title", feedList.get(position - 1).title);
					intent_com.putExtra("type", AppEnums.EnumContentType.blog);
					startActivity(intent_com);
					break;
				case 2:
					Intent intent_author = new Intent();
					intent_author.setClass(CnblogsMainActivity.this, AuthorHomePage.class);
					intent_author.putExtra("blogapp", feedList.get(position - 1).blogapp);
					startActivity(intent_author);
					break;
				default:

					break;
				}
			}
		}).create().show();
		return true;
	}

	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v == title_include_channel_btn) {
			if (!isShow) {
				popupWindow.showAsDropDown(title_include_channel_btn, 10, 10);
				// 使其聚集
				popupWindow.setFocusable(true);
				// 设置允许在外点击消失
				popupWindow.setOutsideTouchable(true);
				// 刷新状态
				popupWindow.update();
				title_include_channel_btn.setBackgroundResource(R.drawable.channel_btn_click);
				isShow = true;
			} else {
				popupWindow.dismiss();
			}
		} else if (v == title_right_menu) {
			if (sp.GetSessionID().equals("")) {
				Intent intent = new Intent();
				intent.setClass(this, UserLoginActivity.class);
				startActivity(intent);
			} else {

				if (!rightIsShow) {
					rightMenuWindow.showAsDropDown(title_right_menu, -20, 0);
					// 使其聚集
					rightMenuWindow.setFocusable(true);
					// 设置允许在外点击消失
					rightMenuWindow.setOutsideTouchable(true);
					// 刷新状态
					rightMenuWindow.update();
					rightIsShow = true;
				} else {
					rightMenuWindow.dismiss();
				}
			}
		} else if (v == right_menu_user_btn) {
			Intent intent = new Intent();
			intent.setClass(this, UserCenterActivity.class);
			startActivity(intent);
			rightMenuWindow.dismiss();
		}
		else if(v==right_menu_ing_btn)
		{
			Intent intent = new Intent();
			intent.setClass(this, IngActivity.class);
			startActivity(intent);
			rightMenuWindow.dismiss();
		}
		else if (v == right_menu_write_btn) {
			Intent intent = new Intent();
			intent.setClass(this, BlogPublicActivity.class);
			startActivity(intent);
			rightMenuWindow.dismiss();
		} else if (v == right_menu_collect_btn) {
			Intent intent = new Intent();
			intent.setClass(this, FavoriteActivity.class);
			startActivity(intent);
			rightMenuWindow.dismiss();
		}
	}
}
